package com.czh.oss.utils;

import com.czh.oss.entity.FileInfo;
import com.czh.oss.enums.ViewContentTypeEnum;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import jakarta.annotation.Resource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author caozaihui
 * @version 1.0
 * @description: MinIo文件操作工具
 * @since 2024/8/17 上午 12:27
 */
@Component
public class MinIoUtil {
    Logger logger = LogManager.getLogger(MinIoUtil.class);

    @Value(value = "${minio.url}")
    private String url;

    @Resource
    private MinioClient minioClient;

    /**
     * 创建一个存储桶
     *
     * @param bucketName
     * @throws ServerException
     * @throws InsufficientDataException
     * @throws ErrorResponseException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws InvalidResponseException
     * @throws XmlParserException
     * @throws InternalException
     */
    public void createBucket(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (isExist) {
            logger.warn("Bucket {} 已存在.", bucketName);
        } else {
            // Create a new bucket called ascii-bucket.
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            logger.info("Bucket {} 创建成功", bucketName);
        }
    }

    /**
     * 上传文件
     *
     * @param inputStream
     * @param bucketName
     * @param objectName
     */
    public void uploadObject(InputStream inputStream, String bucketName, String objectName) {
        try {
            minioClient.putObject(
                    PutObjectArgs.builder().
                        bucket(bucketName).
                        object(objectName).contentType(ViewContentTypeEnum.getContentType(objectName)).
                        stream(inputStream, -1, Integer.MAX_VALUE).
                        build());
            logger.info("向 {} 上传文件 {} 成功",bucketName,objectName);
        } catch (ErrorResponseException | InsufficientDataException | ServerException | XmlParserException |
                 NoSuchAlgorithmException | IOException | InvalidResponseException | InvalidKeyException |
                 InternalException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 列出所有桶
     */
    public List<String> getAllBuckets() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        return minioClient.listBuckets().stream().map(Bucket::name).collect(Collectors.toList());
    }

    /**
     * 列出桶中的所有文件
     * @param bucketName
     */
    public  List<FileInfo> getAllObjects(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
        LinkedList<FileInfo> fileInfos = new LinkedList<>();
        for (Result<Item> itemResult : results) {
            FileInfo fileInfo = new FileInfo();
            fileInfo.setFileName(itemResult.get().objectName());
            fileInfo.setSize(itemResult.get().size());
            fileInfo.setOwner(itemResult.get().owner().displayName());
            fileInfo.setLastModified(itemResult.get().lastModified().toLocalDate());
            fileInfo.setEtag(itemResult.get().etag());
            fileInfo.setStorageClass(itemResult.get().storageClass());
            fileInfo.setDir(itemResult.get().isDir());
            fileInfos.add(fileInfo);
        }
        return fileInfos;
    }
    /**
     * 获取文件url
     * @param bucketName
     * @param objectName
     */
    public String getFileUrl(String bucketName, String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
//        GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
//                .method(Method.GET)
//                .bucket(bucketName).object(objectName).build();
        return url + "/" + bucketName + "/" + objectName;
    }
    /**
     * 获取文件
     * @param bucketName
     * @param objectName
     */
    public InputStream getObject(String bucketName, String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }

    /**
     * 删除桶
     * @param bucketName
     */
    public void deleteBucket(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
        logger.warn("删除存储桶 {} 成功",bucketName);
    }
    /**
     * 删除文件
     * @param bucketName
     * @param objectName
     * */
    public void deleteObject(String bucketName, String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
        logger.warn("{} 中的文件 {} 已删除!",bucketName,objectName);
    }
}
